#!/usr/bin/env python3
"""
Command-line interface for generating and executing Manim animations.

This script provides a simple interface for users to generate and execute Manim animations
using the Anthropic API. It supports various quality settings and execution options.

Usage:
    python generate_animation.py "Create an animation of a circle transforming into a square"
    python generate_animation.py "Explain calculus derivatives" -o my_animation.py -q h
"""

import os
import sys
import argparse
from manim.llm import generate_manim_code, save_code_to_file
from manim.execute_manim import execute_manim_file



def create_argument_parser():
    """Create and configure the argument parser."""
    parser = argparse.ArgumentParser(
        description="Generate and execute Manim animations using Anthropic API",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Generate a simple animation
  python generate_animation.py "Create an animation of a circle transforming into a square"

  # Generate an animation with a specific output file
  python generate_animation.py "Create an animation of a circle transforming into a square" -o my_animation.py

  # Generate an animation with high quality
  python generate_animation.py "Create an animation of a circle transforming into a square" -q h

  # Generate an animation without previewing it
  python generate_animation.py "Create an animation of a circle transforming into a square" -n

  # Only execute an existing animation file
  python generate_animation.py "dummy" -e -o existing_animation.py
"""
    )
    parser.add_argument(
        "search_papers",
        type=str,
        help="search_papers Parmas",
        default="False"
    )
    parser.add_argument(
        "prompt",
        type=str,
        help="Prompt describing the animation to generate"
    )
    parser.add_argument(
        "paper_query",
        type=str,
        help="paper_query describing the animation to generate"
    )
    parser.add_argument(
        "--output", "-o",
        type=str,
        default="generated_animation.py",
        help="Output file for the generated code"
    )
    parser.add_argument(
        "--model", "-m",
        type=str,
        default="claude-sonnet-4-20250514",
        help="Anthropic model to use"
    )
    parser.add_argument(
        "--quality", "-q",
        type=str,
        choices=["l", "m", "h"],
        default="h",
        help="Quality of the animation (l=low, m=medium, h=high)"
    )
    parser.add_argument(
        "--no-preview", "-n",
        action="store_true",
        help="Don't preview the animation after generation"
    )
    parser.add_argument(
        "--execute-only", "-e",
        action="store_true",
        help="Only execute the animation, don't generate new code"
    )


    return parser


def validate_arguments(args):
    """Validate command line arguments."""
    if args.execute_only:
        if not os.path.exists(args.output):
            print(f"Error: File {args.output} does not exist.")
            return False

    # Validate output file extension
    if not args.output.endswith('.py'):
        print("Warning: Output file should have .py extension")

    return True


def execute_only_mode(args):
    """Handle execute-only mode."""
    print(f"Executing animation from {args.output}...")
    return execute_manim_file(args.output, args.quality, not args.no_preview)


def generate_and_execute_mode(args):
    """Handle generation and execution mode."""
    print(f"Generating Manim code for: {args.prompt}")

    # Generate the code
    generated_code = generate_manim_code(args.prompt, args.model)

    if not generated_code:
        print("Failed to generate code.")
        return 1

    # Save the code to file
    output_file = save_code_to_file(generated_code, args.output)
    if not output_file:
        print("Failed to save generated code.")
        return 1

    print(f"Code saved to {output_file}")

    # Execute the generated code
    print("Executing generated code...")
    return execute_manim_file(output_file, args.quality, not args.no_preview)


def main():
    """Main entry point for the script."""
    parser = create_argument_parser()
    args = parser.parse_args()

    # Validate arguments
    if not validate_arguments(args):
        return 1

    try:
        if args.execute_only:
            return execute_only_mode(args)
        else:
            return generate_and_execute_mode(args)

    except KeyboardInterrupt:
        print("\nOperation cancelled by user.")
        return 1
    except Exception as e:
        print(f"Unexpected error: {e}")
        return 1


if __name__ == "__main__":
    sys.exit(main())